package com.leyou.auth.service;

import com.leyou.auth.client.UserClient;
import com.leyou.auth.config.JwtProperties;
import com.leyou.auth.entity.UserInfo;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.user.pojo.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;

/**
 * @author CHERRY
 * @date 2018-09-16-19:20
 */
@Service
@EnableConfigurationProperties(JwtProperties.class)
public class AuthService {

    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private UserClient userClient;

    private Logger LOGGER = LoggerFactory.getLogger(AuthService.class);

    public String authentication(String username, String password) {
        try {

            //验证用户是否存在
            User user = userClient.login(username, password);

            if (user == null) {
                return null;
            }

            String token = JwtUtils.generateToken(new UserInfo(user.getId(), username),
                    jwtProperties.getPrivateKey(), jwtProperties.getExpire());
            return token;
        } catch (Exception e) {

            LOGGER.error("生成token异常", e);

            return null;
        }

    }
}
